import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:intl/intl.dart';
import 'package:largefriends/config/lf_route.dart';
import 'package:largefriends/entity/entities/lf_user_entity.dart';
import 'package:largefriends/net/lf_api_url.dart';
import 'package:largefriends/net/lf_dio_util.dart';
import 'package:largefriends/net/lf_image_upload.dart';
import 'package:largefriends/pages/lf_register/lf_register_logic.dart';
import 'package:largefriends/res/lf_color.dart';
import 'package:largefriends/res/lf_double_ext.dart';
import 'package:largefriends/res/lf_fonts.dart';
import 'package:largefriends/res/lf_text_style.dart';
import 'package:largefriends/res/strings/lf_strings.dart';
import 'package:largefriends/service/lf_auth_service.dart';
import 'package:largefriends/utils/lf_dialog_utils.dart';
import 'package:largefriends/widgets/lf_button.dart';
import 'package:largefriends/widgets/lf_image_picker.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../../../net/error_handle.dart';

class LfRegisterPhotoPage extends StatefulWidget {
  const LfRegisterPhotoPage({super.key});

  @override
  State<LfRegisterPhotoPage> createState() => _LfRegisterPhotoPageState();
}

class _LfRegisterPhotoPageState extends State<LfRegisterPhotoPage> {
  final LfRegisterLogic logic = Get.find();
  @override
  Widget build(BuildContext context) {
    return GetBuilder<LfRegisterLogic>(
      builder: (controller) {
        return Container(
          padding: EdgeInsets.symmetric(horizontal: 16.w),
          height: ScreenUtil().screenHeight,
          child: Stack(
            children: [
              Positioned.fill(
                child: SingleChildScrollView(
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Text(
                        strPostProfilePhotoTip.tr,
                        style: lfTextStyle(
                            sp: 17.sp,
                            fontFamily: fontBold,),
                        textAlign: TextAlign.left,
                      ),
                      20.0.sbh,
                      SizedBox(
                        width: ScreenUtil().screenWidth - 32.w,
                        height: ScreenUtil().screenWidth - 32.w,
                        child: Obx(() {
                          return Column(
                            children: [
                              Expanded(
                                flex: 2,
                                child: Row(
                                  children: [
                                    Expanded(
                                      child: _imageItem(0),
                                      flex: 2,
                                    ),
                                    5.h.sbw,
                                    Expanded(
                                        child: Column(
                                      children: [
                                        Expanded(
                                          child: _imageItem(1),
                                        ),
                                        5.h.sbh,
                                        Expanded(
                                          child: _imageItem(2),
                                        )
                                      ],
                                    ))
                                  ],
                                ),
                              ),
                              5.h.sbh,
                              Expanded(
                                flex: 1,
                                child: Row(
                                  children: [
                                    Expanded(
                                      flex: 2,
                                      child: Row(
                                        children: [
                                          Expanded(
                                            child: _imageItem(3),
                                          ),
                                          5.h.sbw,
                                          Expanded(
                                            child: _imageItem(4),
                                          )
                                        ],
                                      ),
                                    ),
                                    5.h.sbw,
                                    Expanded(
                                      child: _imageItem(5),
                                    )
                                  ],
                                ),
                              )
                            ],
                          );
                        }),
                      )
                    ],
                  ),
                ),
              ),
              Positioned(
                  bottom: 20.h,
                  left: 20.w,
                  right: 20.w,
                  child: Obx(() {
                    var enable = logic.photos.isNotEmpty;
                    return LfButton(
                      enabled: enable,
                      text: strContinue.tr,
                      onPress: () {
                        register();
                      },
                    );
                  }))
            ],
          ),
        );
      },
    );
  }

  _imageItem(int index) {
    if (index >= logic.photos.length) {
      return InkWell(
        child: Container(
          decoration: BoxDecoration(
            color: color8F8F8F,
            borderRadius: 10.r.radius,
          ),
          alignment: Alignment.center,
          child: Icon(
            Icons.add,
            color: colorFF007F,
            size: 32.r,
          ),
        ),
        onTap: () {
          LfImagePicker.pickerImage((file) {
            logic.photos.clear();
            logic.photos.addAll(file);
          }, maxCount: 6 - logic.photos.length, selected: logic.photos);
        },
      );
    } else {
      return LayoutBuilder(builder: (context, constant) {
        return Stack(
          children: [
            ClipRRect(
                borderRadius: BorderRadius.all(Radius.circular(10.r)),
                child: AssetEntityImage(
                  logic.photos[index],
                  isOriginal: false,
                  fit: BoxFit.cover,
                  width: constant.maxWidth,
                  height: constant.maxHeight,
                )),
            Align(
              alignment: Alignment.topRight,
              child: InkWell(
                child: Container(
                  decoration:
                      BoxDecoration(color: color210215, shape: BoxShape.circle),
                  margin: EdgeInsets.symmetric(horizontal: 6.w, vertical: 6.h),
                  child: Icon(
                    Icons.close,
                    color: Colors.white,
                    size: 22.r,
                  ),
                ),
                onTap: () {
                  logic.photos.removeAt(index);
                },
              ),
            )
          ],
        );
      });
    }
  }

  void register() async {
    showLoading();
    var image = logic.photos.first;

    await uploadFile(fileList: [image]).then((value) async {
      if (value.isEmpty) {
        hideLoading();
        return;
      }
      Map<String, dynamic> params = {
        "user[matchGender]": 3,
        "user[gender]": logic.gender.value,
        "user[avatar]": value.first.attachId,
        "user[username]": logic.username.value.trim(),
        "user[password]": logic.password.value.trim(),
        "user[email]": logic.email.value.trim(),
        'user[birthday]': DateFormat('yyyy-MM-dd').format(
            DateTime.fromMillisecondsSinceEpoch(
                logic.birthday.value!.millisecondsSinceEpoch * 1000))
      };
      await LfDio().post<LfUserEntity>(url: apiRegister, params: params).then(
          (value) {
        hideLoading();
        LfAuthService service = Get.find();
        service.setUserEntity(value);
        if (logic.photos.length > 1) {
          service.uploadProfilePhotos(
              logic.photos.sublist(1, logic.photos.length));
        }
        Get.offAllNamed(LFRoute.pathLogin);
      }, onError: (error) {
        hideLoading();
        if (error is NetError) {
          showSnackBar(error.msg);
        }
      });
    }, onError: (error) {
      hideLoading();
      if (error is NetError) {
        showSnackBar(error.msg);
      }
    });
  }
}
